#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author  :
# @File    : temp.py
# @Software: PyCharm
# @description : XXX


import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import optparse


class SendEmail(object):

    def __init__(self):
        super(SendEmail, self).__init__()
        # 第三方 SMTP 服务
        self._smtp_host = "smtp.mxhichina.com"  # 设置服务器
        self._smtp_port = 465  # 设置服务器
        self._email_user = "alert@jydata.com"  # 用户名
        self._email_pass = "Jydata123456"  # 口令

        self.frm = None
        self.email_pwd = None
        self.to = None
        self.email_title = None
        self.email_content = None
        self.attach_path = None
        pass

    def set_args(self, frm, pwd, to, email_title, email_content, attach_path):
        # from, to, 邮件标题, 邮件内容, 附件路径
        self.frm = frm if frm else self._email_user
        if frm:
            if not pwd:
                raise Exception('please input password')
            else:
                self.email_pwd = pwd
        self.to = to
        self.email_title = email_title
        self.email_content = email_content
        self.attach_path = attach_path
        pass

    def send_email(self):
        multi_part = MIMEMultipart()

        # multi_part['From'] = self.frm
        multi_part['From'] = self._email_user
        # multi_part['To'] = ','.join(receiverList)
        multi_part['To'] = self.to
        multi_part['Subject'] = Header(self.email_title, "utf-8")

        message = self.email_content
        email_body = MIMEText(message, 'plain', 'utf-8')

        multi_part.attach(email_body)
        if self.attach_path is not None:
            attach_path_list = self.attach_path if ',' not in self.attach_path else self.attach_path.split(',')
            if isinstance(attach_path_list, str):
                # 只有一个附件
                attach = MIMEText(open(self.attach_path, 'rb').read(), 'base64', 'utf-8')
                attach["Content-Type"] = 'application/octet-stream'

                # filename not strict
                attach_file_name = attach_path_list.split('/')[-1]
                attach["Content-Disposition"] = 'attachment; filename="{0}"'.format(attach_file_name)
                multi_part.attach(attach)
            else:
                # 多个附件
                for item in attach_path_list:
                    attach = MIMEText(open(item, 'rb').read(), 'base64', 'utf-8')
                    attach["Content-Type"] = 'application/octet-stream'

                    # filename not strict
                    attach_file_name = item.split('/')[-1]
                    attach["Content-Disposition"] = 'attachment; filename="{0}"'.format(attach_file_name)
                    multi_part.attach(attach)

        # ssl 协议安全发送
        smtp_server = smtplib.SMTP_SSL(host=self._smtp_host, port=self._smtp_port)
        try:
            smtp_server.login(self._email_user, self._email_pass)
            smtp_server.sendmail(self.frm, self.to, multi_part.as_string())
        except smtplib.SMTPException as e:
            print("send fail", e)
        else:
            print("send success")
        finally:
            try:
                smtp_server.quit()
            except smtplib.SMTPException:
                print("quit fail")
            else:
                print("quit success")


if __name__ == '__main__':
    parse = optparse.OptionParser(usage='"usage : %prog [options] arg1,arg2"', version="%prog 1.2")
    parse.add_option(
        '-t', '--to', dest='to', action='store', type=str, metavar='to',
        help='please input To email add'
    )
    parse.add_option(
        '-f', '--from', dest='frm', type=str, metavar='from',
        help='please input From email add'
    )
    parse.add_option(
        '-p', '--pwd', dest='pwd', type=str, metavar='pwd',
        help='please input Password'
    )
    parse.add_option(
        '-T', '--emailtitle', dest='emailtitle', type=str, metavar='emailtitle',
        help='please input email title'
    )
    parse.add_option(
        '-C', '--emailcontent', dest='emailcontent', type=str, metavar='emailcontent',
        help='please input email content'
    )
    parse.add_option(
        '-A', '--attachpath', dest='attachpath', type=str, metavar='attachpath',
        help='please input email attach path'
    )
    parse.add_option('-v', help='help')

    options, args = parse.parse_args()
    # print('from : {0}'.format(options.frm))
    # print('pwd : {0}'.format(options.pwd))
    # print(f'to : {options.to}')
    # print(f'emailtitle : {options.emailtitle}')
    # print(f'emailcontent : {options.emailcontent}')
    # print(f'attachpath : {options.attachpath}')
    # print(f'attachpath : {type(options.attachpath)}')

    temp_send = SendEmail()
    temp_send.set_args(
        frm=options.frm, pwd=options.pwd, to=options.to,
        email_title=options.emailtitle,
        email_content=options.emailcontent,
        attach_path=options.attachpath
    )
    temp_send.send_email()